import ffmpeg from 'fluent-ffmpeg';
import { VTS } from './jxt.js';
import { timeStringToSeconds } from '../common.js';
ffmpeg.setFfmpegPath('C:\\ffmpeg\\bin\\ffmpeg.exe');

process.on('message', async task => {
    const { filelistName, nameX, nameW } = JSON.parse(task);
    console.log(`${nameW}正在检测零散文件...`);

    const vts = new VTS();
    vts.on('progress', ({ i, len }) => {
        process.send(JSON.stringify({ i, len, type: 'progressT', nameW }));
    });
    const timeNum = await vts.vtss(filelistName, nameW);
    if (typeof timeNum === 'object' && timeNum.type === 0) {
        console.log(`任务出错,计时为0`);
        process.send(
            JSON.stringify({
                timemark: 0,
                timeend: 0,
                type: 'error',
                nameW,
                dirEnt: timeNum.dirEnt
            })
        );
        return;
    }

    const command = ffmpeg();
    command
        .input(filelistName)
        .inputFormat('concat') // 使用 concat 协议
        .inputOptions(['-safe 0']) // 允许不安全的文件路径
        .videoCodec('hevc_nvenc') // 使用 NVIDIA 硬件编码器
        .audioCodec('aac') // 音频编码器
        .output(nameX)
        .on('start', () => {
            process.send(JSON.stringify({ timemark: 0, timeend: timeNum, type: 'start', nameW }));
        })
        .on('progress', progress => {
            const timemark = progress.timemark === 'N/A' || !progress.timemark ? '00:00:00' : progress.timemark;
            process.send(
                JSON.stringify({
                    timemark: timeStringToSeconds(timemark),
                    timeend: timeNum,
                    type: 'progress',
                    nameW
                })
            );
        })
        .on('end', () => {
            process.send(
                JSON.stringify({
                    timemark: 0,
                    timeend: timeNum,
                    type: 'end',
                    nameW
                })
            );
        })
        .on('error', err => {
            process.send(
                JSON.stringify({
                    timemark: 0,
                    timeend: timeNum,
                    type: 'error',
                    nameW
                })
            );
        })
        .run();
});
